import { Service } from "@/lib";
import { Cover } from "../../Component/Cover";
import { useCallback, useState } from "react";
import { Button, Image } from "antd";
import defaultImage from "../../../../img/defaultImg.gif";
import styles from "./style.module.scss";
import { CloseOutlined } from "@ant-design/icons";

interface ImagesProps {
    value?: string[];
    onChange?: (value: string[]) => void;
    reviewRight?: boolean;
    disabled?: boolean;
    description?: string|React.ReactNode;
    validate?: (file:File) => boolean;
};
const Images = ({ value, onChange, reviewRight, disabled, description, validate }: ImagesProps) => {
    const serviceApi = Service.useService();
    const [ imgPref ] = useState(() => serviceApi.getUrl("resource.mediaUrl"));
    const [ imgList, setImgList ] = useState<string[]>(value || []);
    const formatImageUrl = useCallback((value: string) => {
        return value ? imgPref + "/" + value : defaultImage;
    }, []);
    return (
        <div>
            <Cover hidePreview validate={validate} onChange={(fileId: string) => {
                const newImgList = [...imgList, fileId];
                setImgList(newImgList);
                typeof onChange === "function" && onChange(newImgList);
            }}/>
            <section>
                {
                    imgList.map((item, index) => {
                        return (
                            <section key={index} className={styles.imageButton} >
                                <Image src={formatImageUrl(item)} alt="" style={{ display: "block", width: 80, height: 80 }}/>
                                {(!reviewRight && !disabled) && <button type="button" className={styles.deleteButton} onClick={() => {
                                    const newImgList = imgList.filter((img) => img !== item);
                                    setImgList(newImgList);
                                    typeof onChange === "function" && onChange(newImgList);
                                }}>
                                    <CloseOutlined />
                                </button> }
                            </section>
                        );
                    })
                }
            </section>
             <section className={styles.imageSizeRequirement}>
                <h4>图片要求</h4>
                <p>1. 图片格式统一为“JPG”格式。</p>
                <p>2. 单张图片大小需≤1MB，分辨率≥300dpi，画质清晰，主题突出。</p>
                {description}
            </section>
        </div>
    );
};

export const uploadValidate = (file: File) => {
    return file.size <= 1048576;
};

export default Images;
